#!/usr/bin/env python3

import os
import platform
import shlex
import shutil
import subprocess

import common

class UserlandComponent(self.Component):
    def add_parser_arguments(self, parser):
        parser.add_argument(
            '--has-package',
            action='append',
            default=[],
            help='''\
Indicate that a given package is present in the root filesystem, which
allows us to build examples that rely on it.
''',
        )
        parser.add_argument(
            '--host',
            default=False,
            help='''\
Build the userland programs for the host instead of guest.
Use the host packaged cross toolchain.
''',
        )
        parser.add_argument(
            '--make-args',
            default='',
        )
        parser.add_argument(
            'targets',
            default=[],
            help='''\
Build only the given userland programs.
Default: build all examples that have their package dependencies met.
For example, an OpenBLAS example can only be built if the target root filesystem
has the OpenBLAS libraries and headers installed.
''',
            nargs='*',
        )

    def do_build(self, args):
        build_dir = self.get_build_dir(args)
        os.makedirs(build_dir, exist_ok=True)
        if kwargs['host']:
            allowed_toolchains = ['host']
        else:
            allowed_toolchains = ['buildroot']
        cc = self.get_toolchain_tool('gcc', allowed_toolchains=allowed_toolchains)
        cxx = self.get_toolchain_tool('g++', allowed_toolchains=allowed_toolchains)
        self.sh.run_cmd(
            (
                [
                    'make', LF,
                    '-j', str(kwargs['nproc']), LF,
                    'ARCH={}'.format(kwargs['arch']), LF,
                    'CCFLAGS_SCRIPT={} {}'.format('-I', kwargs['userland_src_dir']), LF,
                    'COMMON_DIR={}'.format(kwargs['root_dir']), LF,
                    'CC={}'.format(cc), LF,
                    'CXX={}'.format(cxx), LF,
                    'PKG_CONFIG={}'.format(kwargs['buildroot_pkg_config']), LF,
                    'STAGING_DIR={}'.format(kwargs['buildroot_staging_dir']), LF,
                    'OUT_DIR={}'.format(build_dir), LF,
                ] +
                self.sh.add_newlines(['HAS_{}=y'.format(package.upper()) for package in kwargs['has_package']]) +
                shlex.split(kwargs['make_args']) +
                self.sh.add_newlines([os.path.join(build_dir, os.path.splitext(os.path.split(target)[1])[0]) + kwargs['userland_build_ext'] for target in kwargs['targets']])
            ),
            cwd=kwargs['userland_src_dir'],
            extra_paths=[kwargs['ccache_dir']],
        )
        self.copy_dir_if_update_non_recursive(
            srcdir=build_dir,
            destdir=kwargs['out_rootfs_overlay_dir'],
            filter_ext=kwargs['userland_build_ext'],
        )

    def get_argparse_args(self):
        return {
            'description': 'Build our compiled userland examples',
        }

    def get_build_dir(self, args):
        return kwargs['userland_build_dir']

if __name__ == '__main__':
    UserlandComponent().build()
